#include "widget.h"
#include "ui_widget.h"
#include "QtCore"
#include "QtSql"
#include "QtGui"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->update();
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(10000);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Widget::update()
{
    this->on_pushButton_clicked();
    nam = new NetworkAccessManager();

    //m_url.setEncodedUrl("http://127.0.0.1/xampp/xampp.css");
    m_url.setEncodedUrl("http://www.futuremark.com/ticker.xml?lastid=0&lasttype=0&r=0");
    //"http://www.futuremark.com/ticker.xml?lastid={0}&lasttype={1}&r={2}";
    m_request.setUrl(m_url);
    m_reply = nam->get(m_request);
    connect(m_reply, SIGNAL(readyRead()), this, SLOT(replyReadyRead()));
    connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}

void Widget::on_pushButton_clicked()
{
    qDebug() << "dbg";
    this->ui->pushButton->setEnabled(false);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName(
            "DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=E:/ticker-2k.mdb");
    if (!db.open())
    {
        qDebug() << "ng";
        return;
    }
    else
    {
        qDebug() << "ok";
    }
    QSqlQuery query;
    query.exec("SELECT * FROM tbl_ticker");
    while(query.next())
    {

        QString v_vga = query.value(query.record().indexOf("vga")).toString();
        qDebug() << v_vga;
        //doSomething(country);
    }
    this->ui->pushButton->setEnabled(true);
}

void Widget::replyReadyRead()
{
    qDebug() << ("ConsDL::replyReadyRead()");
    this->saveRawHeaders();

    QByteArray bytes = m_reply->readAll();
    qDebug() << ("bytes.size(): %1") << (bytes.size());
    qDebug() << bytes.constData();
}

void Widget::replyFinished()
{
    qDebug() << ("ConsDL::replyFinished()");
    //this->saveRawHeaders();
}

void Widget::saveRawHeaders()
{
    QString dirPath = QDesktopServices::storageLocation(
            QDesktopServices::DesktopLocation);
    QDir dir(dirPath);
    QString filePath = dir.filePath("headers.txt");

    QFile file;
    file.setFileName(filePath);
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);

    QList<QByteArray> headerList = m_reply->rawHeaderList();

    foreach(QByteArray ba, headerList)
    {
        QByteArray headerData = m_reply->rawHeader(ba);
        qDebug() << ba << headerData;
        file.write(ba);
        file.write(": ");
        file.write(headerData);
        file.write("\n");
    }
}
